import axios from 'axios';
// import proxy from '../configs/host';
import { getEndian } from 'utils/path';

const env = import.meta.env.MODE || 'development';
console.log('aaaa:', env);
// const API_HOST = proxy[env].API;

const SUCCESS_CODE = 'OK';
const TIMEOUT = 60000;

export const instance = axios.create({
  baseURL: '',
  timeout: TIMEOUT,
  withCredentials: true,
  headers: {
    // token: 'admin_for_test_asdasd',
    'Content-Type': 'application/json',
    token: `Bearer ${localStorage.getItem('ai_transport_token')}`,
  },
});

// 请求拦截器：校验参数类型
instance.interceptors.request.use((config) => {
  if (config.params && 'page' in config.params) {
    config.params.page = Math.max(1, config.params.page);
  }
  return config;
});

// 响应拦截器：统一解析错误
instance.interceptors.response.use(
  (response) => {
    // 正常 AxiosResponse 场景
    if (response && 'status' in response) {
      // eslint-disable-next-line no-console
      console.log('响应数据: ', response);
      if ((response as any).status === 200) {
        const { data } = response as any;
        if (data?.code === SUCCESS_CODE || data?.code === 200) return data;
        // 有些接口可能不返回 code，但直接返回数据主体
        if (data && !('code' in data)) return data;
        return Promise.reject(data);
      }
      return Promise.reject((response as any)?.data ?? response);
    }

    // 已被解包为 data 的场景（例如前置拦截器返回了 res.data）
    const data = response as any;
    if (data?.code === SUCCESS_CODE || data?.code === 200) return data;
    if (data && !('code' in data)) return data;
    return Promise.reject(data);
  },
  (error) => {
    if (error.response?.status === 422) {
      // 解析并抛出后端校验错误
      throw new Error(`参数错误：${JSON.stringify(error.response.data.errors)}`);
    }
    // 401 统一跳转登录
    const lpath = location.pathname.split('/').pop() || '';
    if (location.pathname.length > 1) {
      if (error?.response?.status === 401 && !['login', 'register', 'reset_password'].includes(lpath)) {
        const endianMap: Record<'用户' | '平台', string> = { 用户: 'client', 平台: 'platform' };
        const key = (getEndian() ?? '平台') as keyof typeof endianMap;
        location.href = `/${endianMap[key]}/login`;
      }
    }
    return Promise.reject(error);
  },
);

export default instance;
